﻿using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApi;
using Newtonsoft.Json;
using WebApi.Model;
using WebApiExtend;
using Microsoft.AspNetCore.Http;

namespace WebApi.Controllers
{
    /// <summary>
    /// 
    /// </summary> 
    public class BaseController : ControllerBase
    {
        #region 属性

        /// <summary>
        /// Http上下文访问器
        /// </summary>
        public readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// 用户ID(Token验签后有值)
        /// </summary>
        public int UserID { get; set; }

        /// <summary>
        /// 用户名称(Token验签后有值)
        /// </summary>
        public string UserName { get; set; }

        /// <summary>
        /// 用户角色集合
        /// </summary>
        public List<int?> UserRoleid { get; set; }

        /// <summary>
        /// 用户信息(Token验签后有值)
        /// </summary>
        public system_user LoginUser { get; set; }

        #endregion

        #region 构造函数

        /// <summary>
        /// 
        /// </summary>
        public BaseController(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;

            InitLogin();
        }

        /// <summary>
        /// 数据库读取上下文
        /// </summary>
        /// <typeparam name="Tentity">数据库实体</typeparam>
        /// <returns></returns>
        internal SqlClient<Tentity> DbContext<Tentity>() where Tentity : class, new()
        {
            return new SqlClient<Tentity>(_httpContextAccessor.HttpContext);
        }
        #endregion

        #region 登录相关

        /// <summary>
        /// 初始化登录信息
        /// </summary>
        private void InitLogin()
        {
            var userID = _httpContextAccessor.HttpContext.Session.GetString("userid");
            var userName = _httpContextAccessor.HttpContext.Session.GetString("username");
            var user = _httpContextAccessor.HttpContext.Session.GetString("User");

            if (!string.IsNullOrEmpty(userID) && !string.IsNullOrEmpty(userName))
            {
                this.UserID = Convert.ToInt32(userID);
                this.UserName = userName;
                this.LoginUser = JsonConvert.DeserializeObject<system_user>(user);
            }
        }
        #endregion

        #region 日志处理
        internal void AddLog(string title, string log)
        {
            //记录日志
            DbContext<system_log>().Insert(new system_log
            {
                error = log, 
                //adduserid = this.UserID,
            });
        } 
        #endregion
    }
}
